package com.lungle.warmdiary.app.content.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.lungle.warmdiary.app.AppConstant;
import com.lungle.warmdiary.app.content.db.helper.CacheSQLiteOpenHelper;
import com.lungle.warmdiary.app.model.response.TesterIndustry;
import com.lungle.warmdiary.app.utils.LogUtils;

import java.util.List;

/**
 * Created by zhangxueyuan on 16/10/9.
 * <p>
 * 亲测师徽章
 */
public class IndustryDAO extends BaseDAO {
    private CacheSQLiteOpenHelper helper;
    private String DB_NAME = AppConstant.CACHE_DB;
    private String TABLE = "T_industry";


    public IndustryDAO(Context context) {
        this.helper = new CacheSQLiteOpenHelper(context, DB_NAME);
    }

    public boolean insert(int industryid, String url, String name) {
        db = helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("industryid", industryid);
        values.put("url", url);
        values.put("name", name);
        long result = db.insert(TABLE, null, values);
        close();
        return result == -1 ? false : true;
    }

    public void insertAll(List<TesterIndustry> list) {
        db = helper.getWritableDatabase();
        db.beginTransaction();

        for (TesterIndustry testerIndustry : list) {
            ContentValues values = new ContentValues();
            values.put("industryid", testerIndustry.getId());
            values.put("url", testerIndustry.getIcon());
            values.put("name", testerIndustry.getName());
            db.insert(TABLE, null, values);

        }
        db.setTransactionSuccessful(); // 设置事务处理成功，不设置会自动回滚不提交
        db.endTransaction(); // 处理完成
        close();
    }


    public void removeAll() {
        db = helper.getWritableDatabase();
        db.delete(TABLE, null, null);
        db.endTransaction();
    }


    public TesterIndustry find(int industryid) {
        db = helper.getReadableDatabase();
        TesterIndustry testerIndustry = new TesterIndustry();
        Cursor cursor = null;
        try {
            cursor = db.rawQuery("select * from " + TABLE + " where industryid=? ", new String[]{String.valueOf(industryid)});
            while (cursor.moveToNext()) {
                testerIndustry.setName(cursor.getString(cursor.getColumnIndex("name")));
                testerIndustry.setIcon(cursor.getString(cursor.getColumnIndex("url")));
                return testerIndustry;
            }
        } catch (Exception e) {
            LogUtils.printLogW(e.getMessage());
        } finally {
            if (cursor != null) cursor.close();
        }

        return testerIndustry;
    }

}
